<template>
  <d2-container>
    <template slot="header" class="query-area">
      <el-form ref="indexForm" :model="indexForm" label-width="100px" style="height:auto">
        <template>
          <el-row class="query-row">
            <el-col :span="5">
               <el-form-item label="供应商名称" prop="supplierName">
                  <el-input type="text" v-model="indexForm.supplierName" placeholder="请输入供应商名称"></el-input>
               </el-form-item>
            </el-col>
            <el-col :span="5">
               <el-form-item label="供应商编码" prop="supplierCode">
                  <el-input type="text" v-model="indexForm.supplierCode" placeholder="请输入供应商编码"></el-input>
               </el-form-item>
            </el-col>
            <el-col :span="4">
						<el-form-item label="状态" prop="status">
							<el-select v-model="indexForm.status" placeholder="请选择状态">
								<el-option label="全部" value=""></el-option>
								<el-option label="暂停合作" value="0"></el-option>
								<el-option label="正常合作" value="1"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
            <el-col :span="6">
						<el-form-item label="创建时间" prop="time">
							<el-date-picker
									v-model="time"
									type="datetimerange"
									:picker-options="pickerOptions"
									range-separator="至"
									start-placeholder="开始日期"
									end-placeholder="结束日期"
									value-format="timestamp"
									align="right"
									:default-time="['00:00:00', '23:59:59']"
								></el-date-picker>
						</el-form-item>
					  </el-col>
            <el-col :span="4">
               <el-form-item>
                  <el-button type="primary" size="medium" @click="submitForm('indexForm')">查询</el-button>
                  <el-button type="primary" size="medium" @click="resetForm('indexForm')">重置</el-button></el-form-item>
            </el-col>
          </el-row>
        </template>
      </el-form>
    </template>
    <template>
      <el-button slot="header" type="primary" style="margin-bottom: 5px" @click="add">新 增</el-button>
      <el-table
        :data="tableData"
        stripe border
        row-key="id"
        @selection-change="handleSelectionChange">
        <el-table-column type="index" label="序号" width="50"></el-table-column>
        <el-table-column prop="supplierName" label="供应商名称"></el-table-column>
        <el-table-column prop="supplierCode" label="供应商编码"></el-table-column>
        <el-table-column prop="personInCharge" label="联系人"></el-table-column>
        <el-table-column prop="phone" label="联系电话"></el-table-column>
        <el-table-column
            align="center"
            prop="status"
            label="状态"
            width="110">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status==0" style="color:#909399;background-color: white;">暂停合作</el-tag>
              <el-tag v-if="scope.row.status==1">正常合作</el-tag>
            </template>
        </el-table-column>
        <el-table-column
            align="center"
            prop="supplierLevel"
            label="供应商等级"
            width="110">
            <template slot-scope="scope">
              {{scope.row.supplierLevel==0?"其它":""}}
              {{scope.row.supplierLevel==1?"省级":""}}
              {{scope.row.supplierLevel==2?"市级":""}}
              {{scope.row.supplierLevel==3?"特约":""}}
              {{scope.row.supplierLevel==4?"独家":""}}
            </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" :formatter="forDateCreate" width="150"></el-table-column>
        <el-table-column prop="reviseTime" label="修改时间" :formatter="forDateRevise" width="150"></el-table-column>
        <el-table-column fixed="right" label="操作" width="300">
          <template slot-scope="scope">
            <el-button v-if="scope.row.status==0" type="success" size="small" @click="restartCooperation(scope.$index, scope.row)">重启</el-button>
            <el-button v-if="scope.row.status==1" type="info" size="small" @click="suspendCooperation(scope.$index, scope.row)">暂停</el-button>
            <el-button type="warning" size="small" @click="updateRow(scope.row.id)">编辑</el-button>
            <el-button
              @click.native.prevent="deleteRow(scope.$index, scope.row)"
              type="danger"
              size="small"
            >删除</el-button>
            <el-button type="primary" size="small" @click="supplierProduct(scope.row.id)">管理商品</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <!-- 页脚部分 -->
		<template slot="footer">
			<div class="page">
				<el-pagination
					background
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
					:current-page="currentPage"
					:page-sizes="[10, 20, 50, 100]"
					:page-size="pageSize"
					layout="total, sizes, prev, pager, next, jumper"
					:total="total"
				></el-pagination>
			</div>
		</template>
    <template>
      <div>
        <keep-alive>
          <addPage
            :addPage="addComponent"
            @on-addPage-change="onAddPageChange"
            @on-loadlist-change="fetchData"
          ></addPage>
        </keep-alive>
      </div>
      <div>
        <keep-alive>
          <updatePage
            :updatePage="updateComponent"
            @on-updatePage-change="onUpdatePageChange"
            @on-loadlist-change="fetchData"
            :uId="updateId"
            @on-id-change="onIdChange"
          ></updatePage>
        </keep-alive>
      </div>
    </template>
  </d2-container>
</template>
<script>
import {
  findAllListByPage,
  unenableSupplierInfo,
  enableSupplierInfo,
  deleteSupplierInfo
} from '@api/supplier/supplier'
import addPage from './supplieradd'
import updatePage from './supplierupdate'
import dayjs from 'dayjs'
export default {
  name: 'supplier-index',
  components: {
    addPage,
    updatePage
  },
  data () {
    return {
      indexForm: {
        supplierName: '',
        supplierCode: '',
        status: '',
        startTime: '',
        endTime: ''
      },
      time: [],
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      multipleSelection: [],
      addComponent: false,
      updateComponent: false,
      updateId: ''
    }
  },

  mounted () {
    this.fetchData()
  },
  methods: {
    fetchData () {
      this.loading = true
      this.indexForm.startTime = this.time[0] == null ? '' : dayjs(this.time[0]).format('YYYY-MM-DD HH:mm:ss')
      this.indexForm.endTime = this.time[1] == null ? '' : dayjs(this.time[1]).format('YYYY-MM-DD HH:mm:ss')
      findAllListByPage({
        supplierName: this.indexForm.supplierName,
        supplierCode: this.indexForm.supplierCode,
        status: this.indexForm.status,
        startTime: this.indexForm.startTime,
        endTime: this.indexForm.endTime,
        currentPage: this.currentPage,
        pageSize: this.pageSize
      }).then(res => {
        this.tableData = res.data.content
        this.total = res.data.total
        this.loading = false
      }).catch(err => {
        console.log('err', err)
        this.loading = false
      })
    },
    handleSizeChange (val) {
      this.pageSize = val
      this.fetchData()
    },
    handleCurrentChange (val) {
      this.currentPage = val
      this.fetchData()
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    resetPage () {
        this.currentPage = 1,
        this.pageSize = 10,
        this.total = 0
    },
    submitForm (formName) {
      this.resetPage()
      this.fetchData()
    },
    resetForm (formName) {
		    this.$refs[formName].resetFields()
        this.time = []
        this.resetPage()
        this.fetchData()
    },
    forDateCreate (row, column) {
      return row.createTime == null
        ? ''
        : dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss')
    },
    forDateRevise (row, column) {
      return row.reviseTime == null
        ? ''
        : dayjs(row.reviseTime).format('YYYY-MM-DD HH:mm:ss')
    },
    restartCooperation (index, row) {
      this.$confirm('是否确定启用【' + row.supplierName + '】供应商？').then(_ => {
        this.loading = true
        enableSupplierInfo({
          supplierId: row.id
        })
          .then(res => {
            var code = res.code
            if (res.code == '000000') {
              this.$message({ message: res.message, type: 'success' })
              this.fetchData()
              this.loading = false
            } else {
              this.$message({ message: res.message, type: 'error' })
            }
          })
          .catch(err => {
            console.log('err', err)
            this.loading = false
          })
      })
    },
    suspendCooperation (index, row) {
      this.$confirm('是否确定停用【' + row.supplierName + '】供应商？').then(_ => {
        this.loading = true
        unenableSupplierInfo({
          supplierId: row.id
        })
          .then(res => {
            var code = res.code
            if (res.code == '000000') {
              this.$message({ message: res.message, type: 'success' })
              this.fetchData()
              this.loading = false
            } else {
              this.$message({ message: res.message, type: 'error' })
            }
          })
          .catch(err => {
            console.log('err', err)
            this.loading = false
          })
      })
    },
    deleteRow (index, row) {
      this.$confirm('确认删除' + row.supplierName + '？').then((_) => {
        this.loading = true
        deleteSupplierInfo({
          supplierId: row.id
        })
          .then((res) => {
            var code = res.code
            if (res.code == '000000') {
              this.$message({ message: res.message, type: 'success' })
              this.fetchData()
              this.loading = false
            } else {
              this.$message({ message: res.message, type: 'error' })
            }
          })
          .catch((err) => {
            console.log('err', err)
            this.loading = false
          })
      })
    },
    add () {
      this.addComponent = !this.addComponent
    },
    onAddPageChange (val) {
      this.addComponent = val // ④外层调用组件方注册变更方法，将组件内的数据变更，同步到组件外的数据状态中
    },
    update () {
      this.updateComponent = !this.updateComponent
    },
    onUpdatePageChange (val) {
      this.updateComponent = val // ④外层调用组件方注册变更方法，将组件内的数据变更，同步到组件外的数据状态中
      if (!this.updateComponent) {
        this.updateId = -1
      }
    },
    updateRow (id) {
      this.update()
      this.idChange(id)
    },
    idChange (val) {
      this.updateId = val
    },
    onIdChange (val) {
      this.updateId = val // ④外层调用组件方注册变更方法，将组件内的数据变更，同步到组件外的数据状态中
    },
    supplierProduct (id) {
      sessionStorage.setItem('supplierId', id)
      this.$router.push({
        path: '/supplier/supplierProductList',
        name: 'supplier-supplierProductList',
        params: ''
      })
    }
  }
}
</script>
